<template>
	<view class="add-food-container">
		<!-- 自定义导航栏 -->
		<view class="custom-nav">
			<view class="nav-left" @tap="goBack">
				<text class="iconfont icon-back"></text>
			</view>
			<view class="nav-title">添加饮食记录</view>
			<view class="nav-right" @tap="saveRecord">
				<text>保存</text>
				<view class="badge" v-if="selectedFoods.length > 0">{{selectedFoods.length}}</view>
			</view>
		</view>
		
		<!-- 主体内容区 -->
		<scroll-view scroll-y class="content-scroll">
			<!-- 餐次选择卡片 -->
			<view class="food-card meal-type-card">
				<view class="meal-type-header">
					<text class="meal-date">{{formatDate}}</text>
					<view class="meal-tabs">
						<view 
							v-for="(item, index) in mealTypes" 
							:key="index"
							class="meal-tab" 
							:class="{ active: mealType === item.value }"
							@tap="selectMeal(item.value)"
						>
							<text class="iconfont" :class="item.icon"></text>
							<text class="tab-text">{{item.label}}</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 已选食物列表卡片 -->
			<view class="food-card selected-foods-card" v-if="selectedFoods.length > 0">
				<view class="card-title">
					<text class="iconfont icon-selected"></text>
					<text>已选食物 ({{selectedFoods.length}})</text>
					<view class="add-more-btn" @tap="startAddingFood">
						<text class="iconfont icon-add"></text>
						<text>添加食物</text>
					</view>
				</view>
				
				<view class="selected-foods-list">
					<view 
						class="selected-food-item"
						v-for="(food, index) in selectedFoods" 
						:key="index"
						:class="{ 'fade-in': food.isNew }"
					>
						<image :src="food.image || '/static/images/placeholder.png'" mode="aspectFill" class="selected-food-img"></image>
						<view class="selected-food-info">
							<view class="selected-food-name">{{food.name}}</view>
							<view class="selected-food-amount">{{food.amount}}{{food.unit || 'g'}}</view>
							<view class="selected-food-calories">{{Math.round(food.calories * food.amount / 100)}}千卡</view>
						</view>
						<view class="selected-food-actions">
							<text class="iconfont icon-edit" @tap.stop="editFood(index)"></text>
							<text class="iconfont icon-delete" @tap.stop="removeFood(index)"></text>
						</view>
					</view>
				</view>
				
				<!-- 总营养素信息 -->
				<view class="total-nutrition">
					<view class="total-nutrition-title">总营养素</view>
					<view class="total-nutrition-info">
						<view class="total-nutrition-item">
							<text class="label">热量</text>
							<text class="value">{{totalCalories}}千卡</text>
						</view>
						<view class="total-nutrition-item">
							<text class="label">碳水</text>
							<text class="value">{{totalCarbs}}g</text>
						</view>
						<view class="total-nutrition-item">
							<text class="label">蛋白质</text>
							<text class="value">{{totalProtein}}g</text>
						</view>
						<view class="total-nutrition-item">
							<text class="label">脂肪</text>
							<text class="value">{{totalFat}}g</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 食物选择卡片 -->
			<view class="food-card food-select-card" v-if="selectedFoods.length === 0 || isAddingFood">
				<view class="card-title">
					<text class="iconfont icon-food"></text>
					<text>食物选择</text>
					<view class="add-more-btn" v-if="isAddingFood && selectedFoods.length > 0" @tap="cancelAddingFood">
						<text class="iconfont icon-back"></text>
						<text>返回</text>
					</view>
				</view>
				
				<!-- 搜索框 -->
				<view class="search-container">
					<view class="search-input-box">
						<text class="iconfont icon-search"></text>
						<input
							type="text"
							v-model="searchKeyword"
							placeholder="搜索食物名称"
							confirm-type="search"
							@input="onSearchInput"
							class="search-input"
						/>
						<text class="iconfont icon-close" v-if="searchKeyword" @tap="clearSearch"></text>
					</view>
				</view>
				
				<!-- 食物列表 -->
				<view class="food-list-container" v-if="!currentFood.id">
					<view class="category-tabs" v-if="!searchKeyword">
						<view 
							v-for="(category, index) in foodCategories" 
							:key="index"
							class="category-tab"
							:class="{ active: currentCategoryId === category.id }"
							@tap="selectCategory(category.id)"
						>
							{{category.name}}
						</view>
					</view>
					
					<view class="food-list">
						<view 
							class="food-item" 
							v-for="(item, index) in displayFoods" 
							:key="index"
							@tap="selectFood(item)"
							:class="{ 'scale-up': item.isSelected }"
						>
							<image :src="item.image || '/static/images/placeholder.png'" mode="aspectFill" class="food-item-img"></image>
							<view class="food-item-info">
								<view class="food-item-name">{{item.name}}</view>
								<view class="food-item-details">
									<text class="food-item-calorie">{{item.calories}}千卡/{{item.unit || '100g'}}</text>
									<text class="food-item-nutrients">碳水{{item.carbs}}g 蛋白{{item.protein}}g 脂肪{{item.fat}}g</text>
								</view>
							</view>
						</view>
						
						<view class="no-results" v-if="displayFoods.length === 0">
							<image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
							<text>暂无食物数据</text>
						</view>
					</view>
					
					<view class="load-more" v-if="hasMoreFoods && displayFoods.length > 0" @tap="loadMoreFoods">
						<view class="load-more-btn" :class="{ 'loading': loadingMore }">
							<text v-if="!loadingMore">加载更多</text>
							<text v-else>加载中...</text>
						</view>
					</view>
				</view>
				
				<!-- 当前选中食物 -->
				<view class="current-food" v-if="currentFood.id">
					<image :src="currentFood.image || '/static/images/placeholder.png'" mode="aspectFill" class="food-img"></image>
					<view class="food-details">
						<view class="food-name">{{currentFood.name}}</view>
						<view class="food-basic-info">
							<text>{{currentFood.calories}} 千卡/{{currentFood.unit || '100g'}}</text>
						</view>
					</view>
					<view class="food-action" @tap="clearCurrentFood">
						<text class="iconfont icon-close"></text>
					</view>
				</view>
				
				<!-- 食物数量选择器 -->
				<view class="amount-selector" v-if="currentFood.id">
					<text class="amount-label">食用量 ({{currentFood.unit || 'g'}})</text>
					<view class="amount-control">
						<button class="amount-btn" @tap="decreaseAmount">
							<text class="iconfont icon-minus"></text>
						</button>
						<input 
							type="number" 
							v-model="amount" 
							class="amount-input"
							@blur="validateAmount"
						/>
						<button class="amount-btn" @tap="increaseAmount">
							<text class="iconfont icon-plus"></text>
						</button>
					</view>
				</view>

				<!-- 营养信息卡片 -->
				<view class="nutrition-info" v-if="currentFood.id">
					<view class="nutrition-grid">
						<view class="nutrition-item">
							<view class="nutrition-value">{{calculatedCalories}}</view>
							<view class="nutrition-label">千卡</view>
							<view class="nutrition-progress">
								<view class="progress-bar" :style="{width: `${Math.min(calculatedCalories/2000*100, 100)}%`}"></view>
							</view>
						</view>
						
						<view class="nutrition-item">
							<view class="nutrition-value">{{calculatedCarbs}}</view>
							<view class="nutrition-label">碳水(g)</view>
							<view class="nutrition-progress">
								<view class="progress-bar carbs-bar" :style="{width: `${Math.min(calculatedCarbs/300*100, 100)}%`}"></view>
							</view>
						</view>
						
						<view class="nutrition-item">
							<view class="nutrition-value">{{calculatedProtein}}</view>
							<view class="nutrition-label">蛋白质(g)</view>
							<view class="nutrition-progress">
								<view class="progress-bar protein-bar" :style="{width: `${Math.min(calculatedProtein/75*100, 100)}%`}"></view>
							</view>
						</view>
						
						<view class="nutrition-item">
							<view class="nutrition-value">{{calculatedFat}}</view>
							<view class="nutrition-label">脂肪(g)</view>
							<view class="nutrition-progress">
								<view class="progress-bar fat-bar" :style="{width: `${Math.min(calculatedFat/70*100, 100)}%`}"></view>
							</view>
						</view>
					</view>
				</view>

				<!-- 添加到饮食按钮 -->
				<view class="add-to-diet-btn" v-if="currentFood.id" @tap="addCurrentFood">
					<text>添加到饮食</text>
				</view>
			</view>
			
			<!-- 时间选择卡片 -->
			<view class="food-card time-card" v-if="selectedFoods.length > 0">
				<view class="card-title">
					<text class="iconfont icon-time"></text>
					<text>日期与时间</text>
				</view>
				
				<view class="datetime-pickers">
					<view class="datetime-item">
						<text class="datetime-label">日期</text>
						<picker 
							mode="date" 
							:value="date" 
							:start="startDate" 
							:end="endDate" 
							@change="dateChange"
							class="datetime-picker"
						>
							<view class="picker-value">
								<text>{{formatDisplayDate}}</text>
								<text class="iconfont icon-arrow-down"></text>
							</view>
						</picker>
					</view>
					
					<view class="datetime-item">
						<text class="datetime-label">时间</text>
						<picker 
							mode="time" 
							:value="time" 
							@change="timeChange"
							class="datetime-picker"
						>
							<view class="picker-value">
								<text>{{time}}</text>
								<text class="iconfont icon-arrow-down"></text>
							</view>
						</picker>
					</view>
				</view>
			</view>
			
			<!-- 备注卡片 -->
			<view class="food-card remark-card" v-if="selectedFoods.length > 0">
				<view class="card-title">
					<text class="iconfont icon-note"></text>
					<text>备注信息</text>
				</view>
				
				<textarea 
					v-model="remark" 
					placeholder="添加备注信息，如食物感受、饭后情况等" 
					class="remark-input"
					maxlength="100"
				></textarea>
				<view class="remark-count">{{remark.length}}/100</view>
			</view>
		</scroll-view>
		
		<!-- 底部保存按钮 -->
		<view class="bottom-btn" @tap="saveRecord" v-if="selectedFoods.length > 0 && !isAddingFood">
			<text>保存记录 ({{selectedFoods.length}})</text>
		</view>
	</view>
</template>

<script setup>
	import { ref, computed, onMounted } from 'vue'
	import { getFoodDetail, addDietRecord, getFoodCategories, getFoodByCategory, searchFood } from '@/common/api/diet.js'
	import { getUserInfo } from '@/common/utils/auth.js'
	
	// 当前编辑的食物
	const currentFood = ref({})
	// 已选食物列表
	const selectedFoods = ref([])
	// 是否在添加食物状态
	const isAddingFood = ref(false)
	// 数量
	const amount = ref(100)
	// 餐次类型
	const mealType = ref('lunch')
	// 日期
	const date = ref('')
	// 时间
	const time = ref('')
	// 备注
	const remark = ref('')
	
	// 食物搜索相关
	const searchKeyword = ref('')
	const foodCategories = ref([])
	const currentCategoryId = ref(1) // 默认选中第一个分类
	const foodList = ref([])
	const page = ref(1)
	const pageSize = ref(10)
	const hasMoreFoods = ref(true)
	const loading = ref(false)
	// 加载更多状态
	const loadingMore = ref(false)
	// 保存中状态
	const isSaving = ref(false)
	
	// 餐次类型选项
	const mealTypes = [
		{ label: '早餐', value: 'breakfast', icon: 'icon-breakfast' },
		{ label: '午餐', value: 'lunch', icon: 'icon-lunch' },
		{ label: '晚餐', value: 'dinner', icon: 'icon-dinner' },
		{ label: '加餐', value: 'snack', icon: 'icon-snack' }
	]
	
	// 格式化日期显示
	const formatDate = computed(() => {
		if (!date.value) return ''
		const dateObj = new Date(date.value)
		const month = dateObj.getMonth() + 1
		const day = dateObj.getDate()
		const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][dateObj.getDay()]
		return `${month}月${day}日 ${weekday}`
	})
	
	// 显示日期格式
	const formatDisplayDate = computed(() => {
		if (!date.value) return ''
		const parts = date.value.split('-')
		if (parts.length !== 3) return date.value
		return `${parts[0]}年${parts[1]}月${parts[2]}日`
	})
	
	// 日期范围
	const startDate = computed(() => {
		const now = new Date()
		const year = now.getFullYear()
		const month = (now.getMonth() + 1).toString().padStart(2, '0')
		const day = now.getDate().toString().padStart(2, '0')
		return `${year - 1}-${month}-${day}`
	})
	
	const endDate = computed(() => {
		const now = new Date()
		const year = now.getFullYear()
		const month = (now.getMonth() + 1).toString().padStart(2, '0')
		const day = now.getDate().toString().padStart(2, '0')
		return `${year}-${month}-${day}`
	})
	
	// 计算总营养素
	const totalCalories = computed(() => {
		return selectedFoods.value.reduce((sum, food) => {
			return sum + Math.round(food.calories * food.amount / 100);
		}, 0);
	});
	
	const totalCarbs = computed(() => {
		return selectedFoods.value.reduce((sum, food) => {
			return sum + parseFloat((food.carbs * food.amount / 100).toFixed(1));
		}, 0).toFixed(1);
	});
	
	const totalProtein = computed(() => {
		return selectedFoods.value.reduce((sum, food) => {
			return sum + parseFloat((food.protein * food.amount / 100).toFixed(1));
		}, 0).toFixed(1);
	});
	
	const totalFat = computed(() => {
		return selectedFoods.value.reduce((sum, food) => {
			return sum + parseFloat((food.fat * food.amount / 100).toFixed(1));
		}, 0).toFixed(1);
	});
	
	// 当前食物的计算营养素
	const calculatedCalories = computed(() => {
		if (!currentFood.value.calories) return 0
		return Math.round(currentFood.value.calories * amount.value / 100)
	})
	
	const calculatedCarbs = computed(() => {
		if (!currentFood.value.carbs) return 0
		return (currentFood.value.carbs * amount.value / 100).toFixed(1)
	})
	
	const calculatedProtein = computed(() => {
		if (!currentFood.value.protein) return 0
		return (currentFood.value.protein * amount.value / 100).toFixed(1)
	})
	
	const calculatedFat = computed(() => {
		if (!currentFood.value.fat) return 0
		return (currentFood.value.fat * amount.value / 100).toFixed(1)
	})
	
	// 初始化日期和时间
	const initDateTime = () => {
		// 获取当前时间
		const now = new Date()
		const year = now.getFullYear()
		const month = (now.getMonth() + 1).toString().padStart(2, '0')
		const day = now.getDate().toString().padStart(2, '0')
		const hours = now.getHours().toString().padStart(2, '0')
		const minutes = now.getMinutes().toString().padStart(2, '0')
		
		// 获取URL参数
		const query = uni.getSystemInfoSync().platform === 'mp-weixin' ? 
			getCurrentPages()[getCurrentPages().length - 1].options : 
			uni.getLaunchOptionsSync().query
		
		// 如果URL中有日期参数，使用它
		if (query && query.date) {
			date.value = query.date
		} else {
			// 否则使用当前日期
			date.value = `${year}-${month}-${day}`
		}
		
		// 如果URL中有餐次类型参数，使用它
		if (query && query.mealType) {
			mealType.value = query.mealType
		}
		
		// 设置当前时间
		time.value = `${hours}:${minutes}`
	}
	
	// 页面加载时初始化日期和时间
	onMounted(() => {
		initDateTime()
		loadFoodCategories()
		
		// 获取URL中的食物ID，如果有的话加载食物详情
		const query = uni.getSystemInfoSync().platform === 'mp-weixin' ? 
			getCurrentPages()[getCurrentPages().length - 1].options : 
			uni.getLaunchOptionsSync().query
		
		if (query && query.foodId) {
			loadFoodDetail(query.foodId)
		}
	})
	
	// 加载食物详情
	const loadFoodDetail = async (foodId) => {
		try {
			uni.showLoading({
				title: '加载中...'
			})
			
			const res = await getFoodDetail({ id: foodId })
			
			if (res.code === 0) {
				currentFood.value = res.data
				isAddingFood.value = true
			} else {
				uni.showToast({
					title: res.message || '加载失败',
					icon: 'none'
				})
			}
		} catch (e) {
			console.error('加载食物详情失败:', e)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}
	
	// 增加数量
	const increaseAmount = () => {
		amount.value = Number(amount.value) + 50
		validateAmount()
	}
	
	// 减少数量
	const decreaseAmount = () => {
		amount.value = Math.max(50, Number(amount.value) - 50)
		validateAmount()
	}
	
	// 验证数量
	const validateAmount = () => {
		const num = Number(amount.value)
		if (isNaN(num) || num <= 0) {
			amount.value = 100
		} else {
			amount.value = Math.round(num)
		}
	}
	
	// 选择餐次
	const selectMeal = (type) => {
		mealType.value = type
	}
	
	// 日期变化
	const dateChange = (e) => {
		date.value = e.detail.value
	}
	
	// 时间变化
	const timeChange = (e) => {
		time.value = e.detail.value
	}
	
	// 选择分类
	const selectCategory = (categoryId) => {
		if (currentCategoryId.value === categoryId) return
		currentCategoryId.value = categoryId
		loadFoodsByCategory()
	}
	
	// 搜索输入
	const onSearchInput = () => {
		// 延时执行搜索，避免频繁请求
		clearTimeout(window.searchTimer)
		window.searchTimer = setTimeout(() => {
			searchFoods()
		}, 500)
	}
	
	// 清除搜索
	const clearSearch = () => {
		searchKeyword.value = ''
		loadFoodsByCategory()
	}
	
	// 选择食物
	const selectFood = (food) => {
		// 添加动画标记
		food.isSelected = true
		
		// 100ms后移除标记以便动画结束
		setTimeout(() => {
			food.isSelected = false
			currentFood.value = food
		}, 100)
	}
	
	// 清除当前选中的食物
	const clearCurrentFood = () => {
		currentFood.value = {}
	}
	
	// 获取食物分类
	const loadFoodCategories = async () => {
		try {
			const res = await getFoodCategories()
			if (res.code === 0 && res.data) {
				foodCategories.value = res.data
				if (foodCategories.value.length > 0) {
					currentCategoryId.value = foodCategories.value[0].id
					loadFoodsByCategory()
				}
			}
		} catch (e) {
			console.error('获取食物分类失败:', e)
			uni.showToast({
				title: '获取食物分类失败',
				icon: 'none'
			})
		}
	}
	
	// 根据分类加载食物
	const loadFoodsByCategory = async (reset = true) => {
		if (loading.value) return
		
		loading.value = true
		
		try {
			if (reset) {
				page.value = 1
				foodList.value = []
			}
			
			const res = await getFoodByCategory({
				categoryId: currentCategoryId.value,
				page: page.value,
				pageSize: pageSize.value
			})
			
			if (res.code === 0 && res.data) {
				if (reset) {
					foodList.value = res.data.list || []
				} else {
					foodList.value = [...foodList.value, ...(res.data.list || [])]
				}
				
				// 判断是否还有更多数据
				hasMoreFoods.value = foodList.value.length < res.data.total
				page.value++
			}
		} catch (e) {
			console.error('加载食物列表失败:', e)
			uni.showToast({
				title: '加载食物列表失败',
				icon: 'none'
			})
		} finally {
			loading.value = false
		}
	}
	
	// 搜索食物
	const searchFoods = async (reset = true) => {
		if (loading.value) return
		
		loading.value = true
		
		try {
			if (reset) {
				page.value = 1
				foodList.value = []
			}
			
			if (!searchKeyword.value.trim()) {
				// 关键字为空时加载当前分类的食物
				await loadFoodsByCategory(reset)
				return
			}
			
			const res = await searchFood({
				keyword: searchKeyword.value,
				page: page.value,
				pageSize: pageSize.value
			})
			
			if (res.code === 0 && res.data) {
				if (reset) {
					foodList.value = res.data.list || []
				} else {
					foodList.value = [...foodList.value, ...(res.data.list || [])]
				}
				
				// 判断是否还有更多数据
				hasMoreFoods.value = foodList.value.length < res.data.total
				page.value++
			}
		} catch (e) {
			console.error('搜索食物失败:', e)
			uni.showToast({
				title: '搜索食物失败',
				icon: 'none'
			})
		} finally {
			loading.value = false
		}
	}
	
	// 加载更多食物
	const loadMoreFoods = () => {
		if (loading.value || loadingMore.value) return
		
		loadingMore.value = true
		
		if (searchKeyword.value) {
			searchFoods(false).finally(() => {
				loadingMore.value = false
			})
		} else {
			loadFoodsByCategory(false).finally(() => {
				loadingMore.value = false
			})
		}
	}
	
	// 开始添加新食物
	const startAddingFood = () => {
		isAddingFood.value = true
		currentFood.value = {}
		amount.value = 100
		// 如果之前有搜索关键词，清空重新开始
		if (searchKeyword.value) {
			searchKeyword.value = ''
			loadFoodsByCategory()
		}
	}
	
	// 取消添加食物
	const cancelAddingFood = () => {
		isAddingFood.value = false
		currentFood.value = {}
		searchKeyword.value = ''
	}
	
	// 添加当前食物到列表
	const addCurrentFood = () => {
		if (!currentFood.value.id) {
			uni.showToast({
				title: '请选择食物',
				icon: 'none'
			})
			return
		}
		
		// 创建一个新的食物对象，包含数量信息
		const newFood = {
			...currentFood.value,
			amount: amount.value,
			isNew: true // 用于添加动画效果
		}
		
		// 添加到已选食物列表
		selectedFoods.value.push(newFood)
		
		// 延迟移除动画标记
		setTimeout(() => {
			if (selectedFoods.value.length > 0) {
				const lastIndex = selectedFoods.value.length - 1
				if (selectedFoods.value[lastIndex]) {
					selectedFoods.value[lastIndex].isNew = false
				}
			}
		}, 500)
		
		// 清空当前选中的食物
		currentFood.value = {}
		
		uni.showToast({
			title: '已添加',
			icon: 'success'
		})
		
		// 如果是第一次添加食物，询问是否继续添加
		if (selectedFoods.value.length === 1) {
			uni.showModal({
				title: '添加成功',
				content: '是否继续添加更多食物？',
				cancelText: '暂不添加',
				confirmText: '继续添加',
				success: (res) => {
					if (res.confirm) {
						// 用户点击继续添加，保持在添加食物状态
						isAddingFood.value = true
					} else {
						// 用户点击暂不添加，退出添加食物状态
						isAddingFood.value = false
					}
				}
			})
		} else {
			// 不是第一次添加，保持在添加食物状态
			isAddingFood.value = true
		}
	}
	
	// 编辑已选食物
	const editFood = (index) => {
		// 设置当前编辑的食物
		currentFood.value = {...selectedFoods.value[index]}
		amount.value = currentFood.value.amount
		
		// 设置为编辑模式
		isAddingFood.value = true
		
		// 从列表中移除该食物
		selectedFoods.value.splice(index, 1)
	}
	
	// 移除已选食物
	const removeFood = (index) => {
		uni.showModal({
			title: '提示',
			content: '确定要移除这个食物吗？',
			success: (res) => {
				if (res.confirm) {
					selectedFoods.value.splice(index, 1)
				}
			}
		})
	}
	
	// 根据搜索关键字或当前分类展示的食物列表
	const displayFoods = computed(() => {
		if (searchKeyword.value) {
			// 搜索模式下展示搜索结果
			return foodList.value
		} else {
			// 非搜索模式下展示当前分类的食物
			return foodList.value
		}
	})
	
	// 获取餐次类型对应的数字
	const getMealTypeNumber = (typeString) => {
		// 确保返回的是数字，不是字符串
		switch (typeString) {
			case 'breakfast':
				return 0;
			case 'lunch':
				return 1;
			case 'dinner':
				return 2;
			case 'snack':
				return 3;
			default:
				// 尝试看是否已经是数字
				const typeNum = parseInt(typeString);
				if (!isNaN(typeNum) && typeNum >= 0 && typeNum <= 3) {
					return typeNum;
				}
				// 默认返回午餐(1)
				return 1;
		}
	}
	
	// 保存记录
	const saveRecord = async () => {
		if (selectedFoods.value.length === 0) {
			uni.showToast({
				title: '请至少添加一种食物',
				icon: 'none'
			})
			return
		}
		
		// 防止重复提交
		if (isSaving.value) return
		
		isSaving.value = true
		
		try {
			uni.showLoading({
				title: '保存中...'
			})
			
			// 将字符串类型的mealType转换为整数
			const mealTypeNum = getMealTypeNumber(mealType.value);
			
			// 处理多个食物数据
			const totalFoods = selectedFoods.value.length;
			let successCount = 0;
			let errorCount = 0;
			
			// 创建日期时间对象
			const dateTimeStr = `${date.value} ${time.value}`;
			
			// 创建批量保存的Promise数组
			const savePromises = selectedFoods.value.map(food => {
				// 验证所有必要的数据字段
				if (!food.id && !food.name) {
					console.error('食物信息缺失');
					return Promise.reject(new Error('食物信息缺失'));
				}
				
				// 创建单个食物的记录数据，确保所有值都有默认值防止null
				const recordData = {
					// 获取用户ID
					userId: getUserInfo()?.id || 6, // 使用默认值6
					
					// 食物基本信息
					foodId: food.id, // 食物ID
					name: food.name, // 食物名称
					amount: food.amount || 100, // 默认100g
					mealType: mealTypeNum, // 使用数字类型
					date: date.value || new Date().toISOString().split('T')[0], // 默认今天
					time: time.value || '12:00', // 默认中午
					remark: remark.value || '',
					
					// 食物营养素信息
					calories: food.calories || 0,
					carbs: food.carbs || 0,
					protein: food.protein || 0,
					fat: food.fat || 0,
					image: food.image || '',
					unit: food.unit || 'g'
				};
				
				// 记录提交的数据，用于调试
				console.log('提交的饮食记录数据:', JSON.stringify(recordData));
				
				// 返回保存单个食物的Promise
				return new Promise((resolve, reject) => {
					addDietRecord(recordData)
						.then(res => {
							if (res.code === 0) {
								resolve(res);
							} else {
								console.error('添加失败, 响应:', JSON.stringify(res));
								reject(new Error(res.msg || '添加失败'));
							}
						})
						.catch(err => {
							console.error('请求异常:', err);
							reject(err);
						});
				});
			});
			
			// 使用Promise.allSettled处理多个请求的结果
			const results = await Promise.allSettled(savePromises);
			
			// 统计成功和失败的数量
			results.forEach(result => {
				if (result.status === 'fulfilled') {
					successCount++;
				} else {
					errorCount++;
					console.error('添加食物记录失败:', result.reason);
				}
			});
			
			// 显示结果
			if (successCount > 0) {
				// 显示多样化的成功消息
				let successMessage = '';
				if (successCount === totalFoods) {
					successMessage = '所有食物添加成功！';
				} else {
					successMessage = `成功添加${successCount}/${totalFoods}项食物`;
				}
				
				uni.showToast({
					title: successMessage,
					icon: 'success',
					duration: 2000
				});
				
				// 延迟返回
				setTimeout(() => {
					uni.navigateBack();
				}, 2000);
			} else {
				uni.showToast({
					title: '添加失败，请重试',
					icon: 'none',
					duration: 2000
				});
			}
		} catch (e) {
			console.error('添加记录失败:', e);
			uni.showToast({
				title: '添加记录失败，请重试',
				icon: 'none',
				duration: 2000
			});
		} finally {
			uni.hideLoading();
			isSaving.value = false;
		}
	}
	
	// 返回上一页
	const goBack = () => {
		uni.navigateBack()
	}
</script>

<style lang="scss">
.add-food-container {
	min-height: 100vh;
	background-color: #f7f8fa;
	display: flex;
	flex-direction: column;
	
	// 自定义导航栏
	.custom-nav {
		height: 90rpx;
		background-color: #8cc9a1;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
		padding-top: var(--status-bar-height);
		position: sticky;
		top: 0;
		z-index: 100;
		
		.nav-left {
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.icon-back {
				font-size: 36rpx;
			}
		}
		
		.nav-title {
			font-size: 34rpx;
			font-weight: 500;
		}
		
		.nav-right {
			font-size: 30rpx;
			position: relative;
			padding-right: 15rpx;
			
			.badge {
				position: absolute;
				top: -10rpx;
				right: -10rpx;
				background-color: #ff6b6b;
				color: white;
				font-size: 20rpx;
				min-width: 32rpx;
				height: 32rpx;
				border-radius: 16rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 0 6rpx;
				font-weight: bold;
			}
		}
	}
	
	// 内容滚动区
	.content-scroll {
		flex: 1;
		padding: 20rpx;
	}
	
	// 卡片通用样式
	.food-card {
		background-color: #fff;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
		padding: 30rpx;
		margin-bottom: 20rpx;
		
		.card-title {
			font-size: 30rpx;
			color: #333;
			font-weight: 500;
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;
			position: relative;
			
			.iconfont {
				margin-right: 10rpx;
				color: #8cc9a1;
				font-size: 32rpx;
			}
			
			.add-more-btn {
				position: absolute;
				right: 0;
				top: 0;
				display: flex;
				align-items: center;
				color: #8cc9a1;
				font-size: 26rpx;
				font-weight: normal;
				
				.iconfont {
					margin-right: 5rpx;
					font-size: 28rpx;
				}
			}
		}
	}
	
	// 餐次选择卡片
	.meal-type-card {
		.meal-type-header {
			.meal-date {
				font-size: 32rpx;
				color: #333;
				font-weight: 500;
				margin-bottom: 20rpx;
			}
			
			.meal-tabs {
				display: flex;
				justify-content: space-between;
				margin-top: 15rpx;
				
				.meal-tab {
					flex: 1;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					padding: 15rpx 0;
					border-radius: 10rpx;
					margin: 0 5rpx;
					background-color: #f7f8fa;
					
					&.active {
						background-color: #e8f5eb;
						
						.iconfont, .tab-text {
							color: #8cc9a1;
							font-weight: 500;
						}
					}
					
					.iconfont {
						font-size: 40rpx;
						color: #999;
						margin-bottom: 10rpx;
					}
					
					.tab-text {
						font-size: 26rpx;
						color: #666;
					}
				}
			}
		}
	}
	
	// 已选食物列表卡片
	.selected-foods-card {
		.selected-foods-list {
			margin-top: 20rpx;
			
			.selected-food-item {
				display: flex;
				padding: 20rpx 0;
				border-bottom: 1px solid #f0f0f0;
				
				&.fade-in {
					animation: fadeIn 0.5s ease;
				}
				
				.selected-food-img {
					width: 100rpx;
					height: 100rpx;
					border-radius: 10rpx;
					background-color: #f0f0f0;
					margin-right: 20rpx;
				}
				
				.selected-food-info {
					flex: 1;
					
					.selected-food-name {
						font-size: 28rpx;
						color: #333;
						margin-bottom: 10rpx;
						font-weight: 500;
					}
					
					.selected-food-amount {
						font-size: 26rpx;
						color: #666;
						margin-bottom: 5rpx;
					}
					
					.selected-food-calories {
						font-size: 24rpx;
						color: #8cc9a1;
						font-weight: 500;
					}
				}
				
				.selected-food-actions {
					display: flex;
					align-items: center;
					padding: 0 10rpx;
					
					.iconfont {
						font-size: 28rpx;
						color: #999;
						padding: 10rpx;
						margin-left: 15rpx;
						
						&:active {
							color: #8cc9a1;
							transform: scale(1.1);
						}
					}
				}
			}
		}
		
		// 总营养素信息
		.total-nutrition {
			margin-top: 30rpx;
			padding-top: 20rpx;
			border-top: 1px dashed #eee;
			
			.total-nutrition-title {
				font-size: 28rpx;
				color: #333;
				font-weight: 500;
				margin-bottom: 15rpx;
			}
			
			.total-nutrition-info {
				display: flex;
				flex-wrap: wrap;
				
				.total-nutrition-item {
					width: 50%;
					padding: 10rpx 15rpx;
					
					.label {
						font-size: 24rpx;
						color: #666;
						margin-right: 10rpx;
					}
					
					.value {
						font-size: 28rpx;
						color: #333;
						font-weight: 500;
					}
				}
			}
		}
	}
	
	// 食物选择卡片
	.food-select-card {
		.search-container {
			margin-bottom: 20rpx;
			
			.search-input-box {
				position: relative;
				height: 80rpx;
				background-color: #f7f8fa;
				border-radius: 10rpx;
				display: flex;
				align-items: center;
				padding: 0 20rpx;
				
				.iconfont {
					color: #999;
					font-size: 32rpx;
					&.icon-search {
						margin-right: 10rpx;
					}
					&.icon-close {
						position: absolute;
						right: 20rpx;
						top: 50%;
						transform: translateY(-50%);
						padding: 10rpx;
					}
				}
				
				.search-input {
					flex: 1;
					height: 100%;
					font-size: 28rpx;
				}
			}
		}
		
		.food-list-container {
			margin-top: 20rpx;
			
			.category-tabs {
				display: flex;
				overflow-x: auto;
				white-space: nowrap;
				padding-bottom: 10rpx;
				margin-bottom: 20rpx;
				
				.category-tab {
					padding: 10rpx 30rpx;
					font-size: 26rpx;
					color: #666;
					background-color: #f7f8fa;
					margin-right: 15rpx;
					border-radius: 30rpx;
					
					&.active {
						background-color: #e8f5eb;
						color: #8cc9a1;
						font-weight: 500;
					}
				}
			}
			
			.food-list {
				.food-item {
					display: flex;
					padding: 20rpx 0;
					border-bottom: 1px solid #f0f0f0;
					transition: transform 0.2s;
					
					&.scale-up {
						transform: scale(0.98);
						background-color: #f9f9f9;
					}
					
					.food-item-img {
						width: 100rpx;
						height: 100rpx;
						border-radius: 10rpx;
						background-color: #f0f0f0;
						margin-right: 20rpx;
					}
					
					.food-item-info {
						flex: 1;
						
						.food-item-name {
							font-size: 28rpx;
							color: #333;
							margin-bottom: 10rpx;
							font-weight: 500;
						}
						
						.food-item-details {
							.food-item-calorie {
								font-size: 24rpx;
								color: #8cc9a1;
								margin-right: 15rpx;
								font-weight: 500;
							}
							
							.food-item-nutrients {
								font-size: 24rpx;
								color: #999;
							}
						}
					}
				}
				
				.no-results {
					padding: 50rpx 0;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					
					.empty-image {
						width: 200rpx;
						height: 200rpx;
						margin-bottom: 20rpx;
					}
					
					text {
						color: #999;
						font-size: 28rpx;
					}
				}
			}
			
			.load-more {
				text-align: center;
				padding: 20rpx 0;
				
				.load-more-btn {
					display: inline-block;
					color: #8cc9a1;
					font-size: 26rpx;
					padding: 10rpx 30rpx;
					background-color: #f0f9f2;
					border-radius: 30rpx;
					transition: all 0.3s;
					
					&.loading {
						background-color: #eee;
						color: #999;
					}
				}
			}
		}
		
		.current-food {
			margin-top: 20rpx;
			display: flex;
			align-items: center;
			background-color: #f9f9f9;
			padding: 15rpx;
			border-radius: 10rpx;
			
			.food-img {
				width: 100rpx;
				height: 100rpx;
				border-radius: 10rpx;
				background-color: #f0f0f0;
				margin-right: 20rpx;
			}
			
			.food-details {
				flex: 1;
				
				.food-name {
					font-size: 28rpx;
					color: #333;
					margin-bottom: 10rpx;
					font-weight: 500;
				}
				
				.food-basic-info {
					font-size: 26rpx;
					color: #666;
				}
			}
			
			.food-action {
				width: 60rpx;
				display: flex;
				justify-content: center;
				
				.iconfont {
					font-size: 28rpx;
					color: #999;
					padding: 10rpx;
				}
			}
		}
		
		.amount-selector {
			margin-top: 20rpx;
			
			.amount-label {
				font-size: 28rpx;
				color: #666;
				margin-bottom: 15rpx;
				display: block;
			}
			
			.amount-control {
				display: flex;
				align-items: center;
				
				.amount-btn {
					width: 70rpx;
					height: 70rpx;
					background-color: #f7f8fa;
					border-radius: 50%;
					color: #333;
					display: flex;
					align-items: center;
					justify-content: center;
					margin: 0;
					padding: 0;
					border: none;
					
					&::after {
						border: none;
					}
					
					.iconfont {
						font-size: 32rpx;
					}
				}
				
				.amount-input {
					flex: 1;
					height: 70rpx;
					background-color: #f7f8fa;
					border-radius: 10rpx;
					margin: 0 20rpx;
					text-align: center;
					font-size: 32rpx;
				}
			}
		}
		
		.nutrition-info {
			margin-top: 25rpx;
			background-color: #f9f9f9;
			padding: 20rpx;
			border-radius: 10rpx;
			
			.nutrition-grid {
				display: flex;
				flex-wrap: wrap;
				
				.nutrition-item {
					width: 50%;
					padding: 10rpx;
					
					.nutrition-value {
						font-size: 30rpx;
						color: #333;
						font-weight: 500;
					}
					
					.nutrition-label {
						font-size: 24rpx;
						color: #666;
						margin: 8rpx 0;
					}
					
					.nutrition-progress {
						height: 8rpx;
						background-color: #eaeaea;
						border-radius: 4rpx;
						overflow: hidden;
						
						.progress-bar {
							height: 100%;
							background-color: #8cc9a1;
							border-radius: 4rpx;
							transition: width 0.3s ease-in-out;
							
							&.carbs-bar {
								background-color: #ffc95c;
							}
							
							&.protein-bar {
								background-color: #5b9df8;
							}
							
							&.fat-bar {
								background-color: #ff9f87;
							}
						}
					}
				}
			}
		}
		
		.add-to-diet-btn {
			text-align: center;
			margin-top: 30rpx;
			background-color: #8cc9a1;
			color: #fff;
			font-size: 28rpx;
			padding: 20rpx 0;
			border-radius: 10rpx;
			transition: all 0.2s;
			
			&:active {
				transform: scale(0.98);
				background-color: darken(#8cc9a1, 5%);
			}
		}
	}
	
	// 时间选择卡片
	.time-card {
		.datetime-pickers {
			display: flex;
			
			.datetime-item {
				flex: 1;
				margin-right: 20rpx;
				
				&:last-child {
					margin-right: 0;
				}
				
				.datetime-label {
					font-size: 28rpx;
					color: #666;
					margin-bottom: 15rpx;
					display: block;
				}
				
				.datetime-picker {
					width: 100%;
					
					.picker-value {
						background-color: #f7f8fa;
						height: 80rpx;
						border-radius: 10rpx;
						display: flex;
						align-items: center;
						justify-content: space-between;
						padding: 0 20rpx;
						font-size: 28rpx;
						color: #333;
						
						.iconfont {
							font-size: 26rpx;
							color: #999;
						}
					}
				}
			}
		}
	}
	
	// 备注卡片
	.remark-card {
		.remark-input {
			width: 100%;
			min-height: 200rpx;
			background-color: #f7f8fa;
			border-radius: 10rpx;
			padding: 20rpx;
			font-size: 28rpx;
			color: #333;
			box-sizing: border-box;
		}
		
		.remark-count {
			text-align: right;
			font-size: 24rpx;
			color: #999;
			margin-top: 10rpx;
		}
	}
	
	// 底部保存按钮
	.bottom-btn {
		height: 100rpx;
		background-color: #8cc9a1;
		color: #fff;
		font-size: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		position: sticky;
		bottom: 0;
		left: 0;
		right: 0;
		transition: all 0.2s;
		
		&:active {
			background-color: darken(#8cc9a1, 5%);
		}
	}
	
	// 动画定义
	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translateY(10rpx);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}
}
</style> 